package com.flydog.taskManager.schedule;

import com.flydog.taskManager.dto.TaskBriefParam;
import com.flydog.taskManager.entity.PeriodicTask;
import com.flydog.taskManager.entity.PhasedTask;
import com.flydog.taskManager.entity.Task;
import com.flydog.taskManager.service.PeriodicTaskService;
import com.flydog.taskManager.service.PhasedTaskService;
import com.flydog.taskManager.service.TaskBriefService;
import com.flydog.taskManager.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Component
@Slf4j
public class UpdateProcessStatusTask {

    @Autowired
    TaskService taskService;

    @Autowired
    TaskBriefService taskBriefService;

    @Autowired
    PhasedTaskService phasedTaskService;

    @Autowired
    PeriodicTaskService periodicTaskService;


    //TODO: 修改循环时间
    @Scheduled(cron = "0 0 * * * ?")
    public void execute() {
        Calendar now = Calendar.getInstance();
        List<PhasedTask> changedPhasedTasks =
                phasedTaskService.setStatusBeforeData(0, now);
        List<PeriodicTask> changedPeriodicTasks =
                periodicTaskService.refreshStatus(now);
        List<String> tasksName = new ArrayList<>();
        for (PhasedTask phasedTask : changedPhasedTasks) {
            tasksName.add(phasedTask.getName());
            TaskBriefParam briefParam = new TaskBriefParam();
            briefParam.setBrief("已超过完成时限，系统自动设置该工作为“未完成”！");
            briefParam.setPhaseTaskId(phasedTask.getId());
            briefParam.setSubject("系统设置为未完成");
            taskBriefService.create(briefParam);
        }
        for (PeriodicTask periodicTask: changedPeriodicTasks) {
            tasksName.add(periodicTask.getName());
            TaskBriefParam briefParam = new TaskBriefParam();
            briefParam.setBrief("已完成一个周期，系统已调整周期时间，并设置相关状态");
            briefParam.setPeriodicTaskId(periodicTask.getId());
            briefParam.setSubject("已完成一个周期");
            taskBriefService.create(briefParam);
        }
        log.info("工作" + tasksName.toString() + "工作状态改变");
    }
}
